$(document).ready(function() {
	// AppView cover whole body. That's why we set
	// el is body
	Invitesq.AppView = Backbone.View.extend({
		el : "#body",

		id : Invitesq.eventId,

		postCollection : new Invitesq.PostCollection(),
		
		locationCollection : new Invitesq.LocationCollection(),
		
		ticketCollection : new Invitesq.TicketCollection(),
		
		editables : ["event-slogan", "event-name", "event-news", "event-description", "event-sub-title"],

		initialize : function() {
			_.bindAll(this, 'render', 'addNewPost', 'attachPostView', 'createEvent', 'createTicket', 'newEvent', 'editEvent', 'saveEvent', 'redirectToEvent', 'enableEdit', 'disableEdit');
			
			// Call reset to bind data to collection
			if (this.id != -1)
			{
				// Load Post list
				if(Invitesq.eventPostList != -1)  {
					this.postCollection.reset(Invitesq.eventPostList);
				}
				if(Invitesq.eventLocationList != -1)  {
					this.locationCollection.reset(Invitesq.eventLocationList);
					Invitesq.locationCollection = this.locationCollection;
					// Assign titles 
					Invitesq.locationCollection.each(function(location,index){
						location.set({title : Invitesq.eventLocationTitles[index]});
						console.log("Assign index " + index  + " " + JSON.stringify(location));
					});
					
				}
				// Load ticket list
				if(Invitesq.eventTicketList != -1){
					this.ticketCollection.reset(Invitesq.eventTicketList);
					Invitesq.ticketCollection  = this.ticketCollection;
				}
				
				
			}
			
			// Bind friend list 
			if (Invitesq.userFriends !=-1 && Invitesq.userFriendsList) Invitesq.userFriendsList.reset(Invitesq.userFriends);
			
			// Call Flexslider if there are slides 
			this.$(".flexslider").flexslider({directionNav:false});
			
			// Create and save a map view 
			this.mapSide =  VM.createView("locationView", function() {
				return new Invitesq.MapSideView();
			});
			
			// Create and save a ticket view 
			this.ticketBox =  VM.createView("ticketBoxView", function() {
				return new Invitesq.TicketCollectionView();
			});
			
			this.render();
			this.disableEdit();
		},

		events : {
			"keyup #post-input" : "addNewPost",
			"click #new-event" : "newEvent",
			"click #new-ticket" : "createTicket",
			"click #edit-event" : "editEvent",
			"click #save-event" : "saveEvent",
			"click #watch-event": "watchEvent",
			"click #new-map" : "createMap",
			"click #new-album": "createAlbum",
			"click #all-photos": "allPhotos"
		},

		render : function() {
			var $this = this;
			
			// Attach posts to event page
			if(this.postCollection)
				this.postCollection.each(function(post) {
					$this.attachPostView(post);
				});
			
			// Attach locations
			// Attach the map side view 
			if (this.mapSide) this.$("#left2").prepend(this.mapSide.$el);
			
			// Attach friend to friend box
			console.log('Friendlist size ' + Invitesq.userFriendsList.size());
			if (Invitesq.userFriendsList.size() != 0){
				friendBox =  new Invitesq.FriendBoxView({
					collection: Invitesq.userFriendsList
				});
				this.$("#rightbar").append(friendBox.render().$el);
			}
			
			// Create the slider for cover album
			if (Invitesq.eventId!=-1)
				$.get('/api/album/event/' + Invitesq.eventId + '/cover-photos/', function(photos){
					photos = JSON.parse(photos);
					$.each(photos, function(i,photo){
						//console.log("photo " + JSON.stringify(photo));
						var photoSlideModel = new Invitesq.PhotoSlideModel({
							id:photo.id,
							index: i,
							src: photo.url,
							progress: 100
						});
						
						Invitesq.flexCollection.add(photoSlideModel);
					})
					
					console.log("Collection " + JSON.stringify(Invitesq.flexCollection));
					
					var sliderView = VM.reuseView("flexSliderView", function() {
						return new Invitesq.FlexPhotoSliderView();
					});
					$this.$(".flexslider").replaceWith(sliderView.render().el);
				})
			
			
			
			// Attach the ticket box 
			if (this.ticketBox)  {
				console.log("Append ticket box " + this.ticketBox.$el.html());
				this.$("#left2").append(this.ticketBox.$el);
			}
			else console.log("No ticket box");
			
			return this;
		},

		// Create new post 
		addNewPost : function(e) {
			var $this = this;
			if(e.keyCode != 13) {
				return;
			}

			postData = {
				"post" : $("#post-input").val(),
				"event_id" : this.id
			};
			post = new Invitesq.PostModel();

			$.post("/api/post/create/", postData, function(data) {
				console.log("data" + data);
				post.set(JSON.parse(data));
				// Set view
				$this.attachPostView(post);
			});

		},
		
		// Add posts to event 
		attachPostView : function(post) {
			postView = new Invitesq.PostView({
				model : post
			});

			this.$("#post-inner").prepend(postView.render().$el);
			this.$("#comment-inner").prepend(postView.render().$el);
			this.$("#post-input").val("");

		},
		
		newEvent : function() {
			var $this = this;
			
			// Create a default event page 
			var event_default = new Invitesq.EventModel();
			$.post('/api/event/create/', event_default.toJSON(), function(newEvent){
				// Rewrite url after create
				newEvent = JSON.parse(newEvent);
				$this.id = newEvent.id;
				Invitesq.eventId = newEvent.id;
				Invitesq.eventCoverId = newEvent.cover_album;
				Invitesq.eventRouter.navigate("/event/?id=" + Invitesq.eventId);
				console.log("New Event created with id  " + Invitesq.eventId);
				
				// Enable edit 
				$this.enableEdit();
			});
		},
		
		// Allow edit event by changing HTML directly
		editEvent : function() {
			if (Invitesq.userData == -1){
				Invitesq.login();
				return;
			}
			this.enableEdit();
			
		},
		
		// Save event function  
		saveEvent : function() {
			// Create a new event model
			newEventModel = new Invitesq.EventModel({
				name : this.$('#event-name').html(),
				organizer : this.$('#event-organizer').html(),
				slogan : this.$('#event-slogan').html(),
				description : this.$('#event-description').html(),
				locations : JSON.stringify(Invitesq.locationCollection),
				tickets : JSON.stringify(Invitesq.ticketCollection)
			});
			console.log("EventModel " +  JSON.stringify(newEventModel))
			
			// Add event model to collection to trigger change event
			// Invitesq.eventData.push(newEventModel.toJSON());
			event_data = newEventModel.toJSON();
			event_data.id = Invitesq.eventId;
			// Decide to update or create new post checking id
			if(Invitesq.eventId && Invitesq.eventId != -1) {
				$.post('/api/event/update/', event_data, this.redirectToEvent);
			} 
			else {
				console.log("Cannot update since event ID is null or -1");
			}
		},

		// Redirect to event page 
		redirectToEvent : function(success) {
			
			$.fancybox.close();
			console.log("success " + success);
			if(Invitesq.eventId && Invitesq.eventId != -1) {
				//window.location = "/event/?id=" + Invitesq.eventId ;
			}
		},
		
		// Add event to user's watch list
		watchEvent : function(){
			if(this.id != -1) {
				console.log("call watch");
				$.get('/api/user_event_list/create/', {id: this.id}, function(watchList){
					console.log(watchList);
				})
			}
		},
		
		// Notify after updated the event
		notifyUpdate : function(success) {
			if(success == 1) {
				console.log("Successfully updated event");
			} else {
				console.log("Failed to update event");
			}
		},
		
		// Enable editable fields
		enableEdit : function () {
			// Hide/show buttons
			this.$(".edit-btns").hide();
			this.$(".event-btns").show();
			this.$("#save-event").show();
			
			// Enable editable fields
			$.each(this.editables, function() {
				$("#" + this).addClass("editable-input");
				$("#" + this).attr("contenteditable", "true");
			});
			
			// Create empty slider
			sliderUploadView = VM.createView("newSliderUploadView", function() {
				return new Invitesq.UploadSliderView();
			});
			this.$(".flexslider").replaceWith(sliderUploadView.render().$el);
			sliderUploadView.initUploader();
			
			// Make map editable
			this.mapSide.enableEdit();
		},
		
		// Disable editable fields
		disableEdit : function () {
			// Hide/show buttons
			this.$(".edit-btns").show();
			this.$(".event-btns").hide();
			this.$("#save-event").hide();
			
			// Disable editable fields
			$.each(this.editables, function() {
				$("#" + this).removeClass("editable");
				$("#" + this).removeAttr("contenteditable", "true");
			});
			
			// Make map uneditable
			this.mapSide.disableEdit();
		},
		
		createEvent : function() {

		},

		createTicket : function() {
			newTicketView = VM.reuseView("newTicketView", function() {
				return new Invitesq.TicketCreateView();
			});
			$.fancybox(newTicketView.render().el);
		},

		createMap : function() {
			mapView = VM.reuseView("mapSideView", function() {
				return new Invitesq.MapSideView();
			});
			$.fancybox(mapView.$el);
		},
		
		createAlbum: function() {
			// Default album + event id
			var defaultAlbum = new Invitesq.AlbumModel();
			defaultAlbum = (defaultAlbum.toJSON())
			defaultAlbum.event_id =  Invitesq.eventId;
			console.log("Default album " + JSON.stringify(defaultAlbum));
			
			// Create album first
			$.post("/api/album/create/",defaultAlbum , function(newAlbum){
				// Parse json 
				newAlbum = JSON.parse(newAlbum);
				// Pass album data + new album id 
				albumView = VM.createView("newAlbumView", function() {
					return new Invitesq.UploadAlbumView({
						albumId: newAlbum.id
					});
				});
				// Open in fancy box
				$.fancybox(albumView.render().$el, {'padding':0});			
				albumView.initUploader();
			});
			
		},
		
		allPhotos: function(){
			$.get("/api/photo/all/", function(data){
				data = JSON.parse(data);
				var photos = _.pluck(data, "url");
				console.log(JSON.stringify(photos));


				$.fancybox(photos, {
					type : 'image',
					prevEffect : 'none',
					nextEffect : 'none',

					closeBtn : false,
					arrows : false,
					nextClick : true,

					helpers : {
						thumbs : {
							width : 50,
							height : 50
						}
					}

				});


			});
		}
	});

	Invitesq.appView = new Invitesq.AppView();
	Backbone.history.start({
		pushState : true
	});
});
